# @Time    : 2019/2/21 13:02
# @Author  : xufqing
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from ..serializers.asset_serializer import DeviceInfoSerializer, DeviceInfoListSerializer, DeviceListSerializer
from common.custom import CommonPagination, RbacPermission
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from ..models import DeviceInfo


class DeviceInfoViewSet(ModelViewSet):
    '''
    字典管理：增删改查
    '''
    perms_map = (
    {'*': 'admin'}, {'*': 'device_all'}, {'get': 'device_list'}, {'post': 'device_create'}, {'put': 'device_edit'},
    {'delete': 'device_delete'})
    queryset = DeviceInfo.objects.all()
    serializer_class = DeviceInfoSerializer
    pagination_class = CommonPagination
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    filter_fields = ('status',)
    search_fields = ('sys_hostname', 'hostname', 'os_type')
    ordering_fields = ('id',)
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (RbacPermission,)

    def get_serializer_class(self):
        # 根据请求类型动态变更serializer
        if self.action == 'list':
            return DeviceInfoListSerializer
        return DeviceInfoSerializer


class DeviceListView(ListAPIView):
    queryset = DeviceInfo.objects.all()
    serializer_class = DeviceListSerializer
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_fields = ('os_type',)
    ordering_fields = ('id',)
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (RbacPermission,)

